/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2025-05-10 22:09:18
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2025-06-07 22:43:26
 * @FilePath: /udp_echo_server/UdpClientMain.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once

#include <iostream>

#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>

// 客户端未来再用服务端的时候，一定要知道服务端的IP地址和端口号
// ./udp_server server-ip server-port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << " Usage: " << argv[0] << "server-ip server-port" << std::endl;
        exit(0);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << " create socket error " << std::endl;
        exit(1);
    }

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = serverport;
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    while (1)
    {
        std::string line;
        std::cout << "Place Enter# ";
        std::getline(std::cin, line);

        int n = sendto(sockfd, line.c_str(), line.size(), 0, (struct sockaddr *)&server, sizeof(server));
        if(n>0)
        {
            struct sockaddr_in temp;
            socklen_t len=sizeof(temp);
            char buffer[1024];
            int m=recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&temp,&len);
            if(m>0)
            {
                buffer[m]=0;
                std::cout<<buffer<<std::endl;
            }
            else{
                break;
            }
        }
        else
        {
            break;
        }
    }

    ::close(sockfd);
    return 0;
}